//
//  SongsViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 5/26/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "SongsViewController.h"

#import "Songs.h"

#import "ParserClass.h"

#import "PostClass.h"

#import "UIManager.h"

#import "SongsTableViewCell.h"

#import <AudioToolbox/AudioToolbox.h>

#import <AVFoundation/AVFoundation.h>

#import "StarRatingView.h"

#import "AppDelegate.h"

@interface SongsViewController (){
    NSURLConnection *theConnection;
    NSMutableData *receivedData;
    NSURL *audioFileURL;
    NSData *dataFromCore;
    float start;
}

@end

@implementation SongsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.tableView setBackgroundColor:[UIColor colorWithRed:28.0/255.0 green:28.0/255.0 blue:28.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar setHidden:YES];
    [self.tableView reloadData];
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [self.tabBarController.tabBar setHidden:YES];
    
    if ([[[ParserClass sharedItems] songDetails]count] == 0) {
        UIAlertView *noSong = [[UIAlertView alloc] initWithTitle:@"" message:@"No Available Songs" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [noSong show];
        
    }
    
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger) buttonIndex
{
    if (buttonIndex == 0)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}



- (IBAction)backAction:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [[[ParserClass sharedItems] songDetails] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    
    static NSString *cellIdentifier = @"Cell";
    
    SongsTableViewCell *cell = (SongsTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SongsTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    Songs *song = [[ParserClass sharedItems] songDetails][indexPath.row];
    
    
    cell.songNameLbl.text = [song songName];
    cell.durationLbl.text = [song durations];
    cell.numberOfDownloads.text = [NSString stringWithFormat:@"No. of downloads: %@", [song downloads]];
    cell.lblBp.text = [NSString stringWithFormat:@"%@ Bp", [song price]];
    
    int likers = [[song ratings] intValue];
    
    NSLog(@"Test Likes %@", [song likes]);
    
    StarRatingView* starViewNoLabel = [[StarRatingView alloc]initWithFrame:CGRectMake(60, 59, 45, 8) andRating:likers withLabel:NO animated:YES];
    
    [starViewNoLabel setUserInteractionEnabled:NO];
    
    [cell.customCell addSubview:starViewNoLabel];
    
    return cell;
    
    
}


#pragma mark - Table view delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"wew");
    
    
    Songs *song = [[ParserClass sharedItems] songDetails][indexPath.row];
    
    [[ParserClass sharedItems] getUrlSong:[NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [song songLocation]] andCount:indexPath.row andFileSize:[song fileSize] andSongPreview:[NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [song songPreview]]];
    
    [[ParserClass sharedItems] getType:@"Songs"];
    
    [self.navigationController pushViewController:[[UIManager sharedItems] playSong] animated:YES];
    
    NSLog(@"Likes Data: %@",[song likes]);
    
    
    
    
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//    if (connection == theConnection)
//    {
//        //        if (delegate && [delegate respondsToSelector:successSelector])
//        //            [delegate performSelector:successSelector
//        //                           withObject:connectionSpecificDataObject];
//        
//        
//        NSLog(@"Finish");
//        
//        
//        
//        
//    }
    
}



-(void)downloadAction:(id)sender{
    
//    NSLog(@"Download");
//    
//    NSURLRequest *theRequest= [NSURLRequest requestWithURL:[NSURL URLWithString:[[ParserClass sharedItems] urlSong]]
//                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
//                                           timeoutInterval:60.0];
//    
//    theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
//    if (theConnection) {
//        // Get Data
//        receivedData = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:[[ParserClass sharedItems] urlSong]]];
//        
//        NSInteger idx = [[ParserClass sharedItems] idxCount];
//        
//        Songs *song = [[ParserClass sharedItems] songDetails][idx];
//        // Album *album = [[ParserClass sharedItems] albumDetails][idx];
//        
//        
//        [((AppDelegate*)[[UIApplication sharedApplication] delegate]) musicDataWithName:[song songName] andData:receivedData andSongID:[song idSong] andImage:[[ParserClass sharedItems] imgAlbum] andDuration:[song durations]];
//        
//        if (!(receivedData == nil)) {
//            
//            NSLog(@"Count Confirmed");
//            
//            [[PostClass sharedItems] downloadCount:[song idSong]];
//            
//        }
//        
//        //NSLog(@"received data = %@", receivedData);
//        
//    } else {
//        // Error handling
//    }
}

- (void)viewDidUnload{

    [super viewDidUnload];
    
    [[ParserClass sharedItems] emptySong];
}



@end
